<?php

namespace app\mos\controller;

use app\common\controller\ActionLogs;
use app\common\controller\Fztest;
use app\common\controller\Platurl;
use app\common\controller\UserBonusFee;
use app\common\model\CardGeneral;
use app\common\model\CardGoods;
use app\common\model\CardGoodsCate;
use app\common\model\CardMember;
use app\common\model\CardOrder;

use app\common\model\CardPaycard;
use app\common\model\CardPaycardlog;
use app\common\model\CardUserGet;

use app\common\model\Agent;
use app\common\model\CardUserUpdate;
use app\common\model\Paylog;
use app\common\model\WxOpen;
use app\common\model\Merchant;
use app\common\model\System;
use app\index\controller\Wxpay;
use think\Config;
use think\Controller;
use think\Request;
use think\Session;
use Wechat\Wxobjopen;
use Wnkj\WnCardObj;

class Cardshoptest extends Mobiletest
{

//    public function orderconf($id){
//        $map['id'] = $id;
//        $CardGoods = new CardGoods();
//        $list =$CardGoods->where($map)->order('id asc')->select();
//        $this->assign('list', $list);
//        return $this->fetch();
//    }

    //会员卡激活跳转
    public function activcardus()
    {
        //获取会员卡信息
        $arr = request()->param();
        $this->_init();
        $appid = $this->getappid($arr['card_id']);
        $usercode = $this->res_user_code($arr);
        if (!empty($usercode)) {
            $openid = Session::get($appid . '_openid');
            if ($openid == $arr['openid']) {
                $maps['card_id'] = $arr['card_id'];
                $CardMember = new CardMember();
                $cardsinfo = $CardMember->where($maps)->find();
                if ($cardsinfo['is_pay'] == 1) {
                    $cardsinfo['orderid'] = $this->getorderid($cardsinfo['mid']);
                    $cardsinfo['user_code']=$usercode;
                    $this->cardpaylogadd($cardsinfo, $arr['openid']);
                    //支付信息
                    $Merchant = new Merchant();
                    $Agent = new Agent();
                    $WxOpen = new WxOpen();
                    $map['id'] = $cardsinfo['mid'];
                    $config = $Merchant->where($map)->find();
                    $agent = $Agent->where(array('id' => $config['agent']))->find();
                    $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
                    $userwx = $WxOpen->where(array('id' => $config['wx_open_id']))->find();

                    $options = array(
                        'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
                        'partnerid' => $agent['partnerid'], // 财付通商户身份标识
                        'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
                    );
                    $weObj = new Wxobjopen($options);
                    $price = $cardsinfo['price'];

                    $appid = $users['authorizer_appid'];
                    $mch_id = $agent['partnerid'];
                    $out_trade_no = $cardsinfo['orderid'];
                    $body = "付费卡购买";
                    $sub_mch_id = $config['sub_mch_id'];
                    $sub_appid = $userwx['authorizer_appid'];
                    $total_fee = $price * 100;
                    $sub_openid = $arr['openid'];
                    $notify_url = 'https://' . $_SERVER ['SERVER_NAME'] . '/api.php';
                    $spbill_create_ip = $_SERVER["REMOTE_ADDR"];
                    $nonce_str = $weObj->generateNonceStr();
                    $pay_xml = $weObj->createPackageXml2($appid, $sub_appid, $mch_id, $sub_mch_id, $nonce_str, $body, $out_trade_no, $total_fee, $spbill_create_ip, $notify_url, '', $sub_openid);
                    $pay_xml = $weObj->get_pay_id($pay_xml);

                    if ($pay_xml['return_code'] == 'SUCCESS') {
                        $prepay_id = $pay_xml['prepay_id'];
                        $jsApiObj["appId"] = $appid;
                        $timeStamp = time();
                        $jsApiObj["timeStamp"] = "$timeStamp";
                        $jsApiObj["nonceStr"] = $nonce_str;
                        $jsApiObj["package"] = "prepay_id=" . $prepay_id;
                        $jsApiObj["signType"] = "MD5";
                        $jsApiObj["paySign"] = $weObj->getPaySignature($jsApiObj);
                        //状态码
                        $this->assign('jsApiObj', json_encode($jsApiObj, JSON_UNESCAPED_UNICODE));
                    } else {
                        $this->error('系统错误:' . $pay_xml['return_msg']);
                    }

                    $this->assign('cardsinfo', $cardsinfo);
                    return $this->fetch();
                } else {
                    $this->error('商家未开启付费功能');
                }
            } else {
                $this->error('非法操作：领卡用户与当前用户信息不匹配');
            }
        }else{
            $this->error("用户信息获取失败，请重新激活");
        }
    }


    private function cardpaylogadd($cinfo, $openid)
    {
        $orderid = $cinfo['orderid'];
        $data['mid'] = $cinfo['mid'];
        $data['openid'] = $openid;
        $data['orderid'] = $orderid;
        $data['price'] = $cinfo['price'];
        $data['cid'] = $cinfo['id'];
        $data['user_code'] = $cinfo['user_code'];
        $CardPaycardlog = new CardPaycardlog();
        $add = $CardPaycardlog->save($data);
        $data['orderid'] = $orderid;
        $data['mid'] = $cinfo['mid'];
        $data['openid'] = $openid;
        $data['pay_statu'] = 0;
        $data['price'] = $cinfo['price'];
        $data['yf_price'] = $cinfo['price'];
        $data['zk_price'] = $data['yf_price'] - $data['price'];
        $data['add_time'] = time();
        $data['attach'] = 'ffcardbuy';
        $data['cz_card_id'] = $cinfo['card_id'];
        $Paylog = new Paylog();
        $add = $Paylog->allowField(true)->save($data);
    }

    //获取用户code
    public function res_user_code($arr)
    {
        $options = $this->options($arr['card_id']);
        $WxObj = new Wxobjopen($options);
        $codedata['encrypt_code'] = $arr['encrypt_code'];
        $resc = $WxObj->decryptCode($codedata);

        if ($resc['errcode'] == 0) {
            if ($resc['code'] == '') {
                $usercode = "";
            } else {
                $usercode = $resc['code'];
            }
            return $usercode;
        }
    }

    //付费购券列表
    public function paycards()
    {
        $this->_init();
        $arr = request()->param();
        $CardPaycard = new CardPaycard();
        if (isset($arr['card_id'])) {
            $appid = $this->getappid($arr['card_id']);
            $card_id = $arr['card_id'];
            $top_mid = $this->gettopmid($card_id);
        } else {
            $appid = $this->getappidmid($arr['mid']);
            $card_id = $this->get_cardid_mid($arr['mid']);
            $top_mid = $this->get_top_mid($arr['mid']);
        }
        //是否领卡会员
        $this->isgetcardus($appid,$card_id,$arr);
        //END
        $map['top_mid'] = $top_mid;
        $map['status'] = 1;
        $map['type'] = 2;
        $list = $CardPaycard->where($map)->select();
        $card['logo_url'] = cardgetinfo($card_id, 0, 0);
        $card['card_id'] = $card_id;
        $this->assign('card', $card);
        $this->assign('list', $list);
        return $this->fetch();
    }

    //是否领卡会员
    public function isgetcardus($appid,$card_id,$arr){

//        try {
            $openid = Session::get($appid . '_openid');
            $map['card_id'] = $card_id;
            $map['openid'] = $openid;
            $map['have'] = 1;
            $map['card_type'] = 'MEMBER_CARD';
            $CardUserGet = new CardUserGet();
            $user = $CardUserGet->where($map)->field('id,openid')->find();
            if (!$user) {
                 $this->redirect('Cardshopnu/paycards', $arr);
            }
//        }catch (\Exception $e){
//            $arrc = json_encode(array('code' => '9099', 'message' => $e->getMessage()));

//        }

    }

    //付费购券详情
    public function paycardsinfo()
    {
        $arr = request()->param();
        $this->_init();
        if (isset($arr['card_id'])) {
            $appid = $this->getappid($arr['card_id']);
            $card_id = $arr['card_id'];
        } else {
            $appid = $this->getappidmid($arr['mid']);
            $card_id = $this->get_cardid_mid($arr['mid']);
        }
        $openid = Session::get($appid . '_openid');
//        var_dump($card_id);
        $map['card_id'] = $card_id;
        $map['openid'] = $openid;
        $map['have'] = 1;
        $map['card_type'] = 'MEMBER_CARD';
        $CardUserGet = new CardUserGet();
        $user = $CardUserGet->where($map)->field('id,openid')->find();

        if ($user) {
            $CardPaycard = new CardPaycard();
            $id = request()->param('fid');
            $map['id'] = $id;
            $map['status'] = 1;
            $info = $CardPaycard->where(array('id' => $id))->find();
            $cardlist = json_decode($info['cardlist'], true);;
            $CardGeneral = new CardGeneral();
            foreach ($cardlist as $k => $v) {
                $cards = $CardGeneral->where(['card_id' => $v['zs_card_id']])->field('color,title,card_id,mid,top_mid,card_type,brand_name,end_timestamp,begin_timestamp')->find();
                $cardlist[$k]['title'] = $cards['title'];
                $cardlist[$k]['color'] = $cards['color'];
                $cardlist[$k]['card_id'] = $cards['card_id'];
                $cardlist[$k]['mid'] = $cards['mid'];
                $cardlist[$k]['top_mid'] = $cards['top_mid'];
                $cardlist[$k]['brand_name'] = $cards['brand_name'];
                $cardlist[$k]['card_type'] = $cards['card_type'];
                $cardlist[$k]['begin_timestamp'] = $cards['begin_timestamp'];
                $cardlist[$k]['end_timestamp'] = $cards['end_timestamp'];
            }
            $info['stocks'] = $info['num'] - $info['get_num'];
            $card['card_id'] = $card_id;
            $this->assign('card', $card);
            $this->assign('user', $user);
            $this->assign('cardlist', $cardlist);
            $this->assign('info', $info);
            return $this->fetch();
        } else {
            $arrs['fid'] = $arr['fid'];
            $arrs['card_id'] = $card_id;
            $this->redirect('Cardshopnu/paycardsinfo', $arrs);
            return $this->fetch('off');
        }
    }

    //付费会员卡
    public function paycardusinfo()
    {
        return $this->fetch();
    }




    //积分商城首页：商品列表
    /*
     * 参数
     * 商品列表
     */
    public function goods($card_id)
    {
        $this->_init();

        $CardOrder = new CardOrder();
        $CardGoodsCate = new CardGoodsCate();
        $map['card_id'] = $card_id;
        $catelist = $CardGoodsCate->where($map)->select();
        $map['statu'] = 0;
        $user = $this->getuserinfo($map);
        $mas['openid'] = $user['openid'];
        $mas['card_id'] = $card_id;
        $order = $CardOrder->where($mas)->order('id desc')->select();
        //END
        //JSSDK
        $share['wxjssdk'] = $this->getsharejssdk($card_id);
        $share['wxjssdk'] = json_encode($share['wxjssdk']);
        $card['card_id'] = $card_id;
        $this->assign('userinfo', $user);
        $this->assign('card', $card);
        $this->assign('share', $share);
        $this->assign('order', $order);
        $this->assign('catelist', $catelist);
        $CardMember = new CardMember();
        $is_bonus_shop = $CardMember->where('card_id', $card_id)->value('is_bonus_shop');
        if ($is_bonus_shop == 1) {
            return $this->fetch('goods');
        } else {
            return $this->fetch('off');
        }
    }

    public function getgoodslist(Request $request){
        if ($request->isAjax()) {
            $param = $request->post();
            $CardGoods = new CardGoods();
            $CardGeneral = new CardGeneral();
            if (!empty($param['cate_id'])) {
                $map['cate_id'] = $param['cate_id'];
            }
            $map['card_id'] = $param['card_id'];
            $map['statu'] = 0;
            $list = $CardGoods->where($map)->order('zs_money asc')->select();
            foreach ($list as $k=>$v){
                if (fileoffcards($v['goods_card_id']) == true){
                    $list[$k] = $v;
                }else{
                    $CardGoods->save(['statu'=>1],['id'=>$v['id']]);
                }
            }
            if ($list) {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = "SUCCESS";
                $rarr['result_code'] = "SUCCESS";
                $rarr['result_msg'] = "请求成功";
                $rarr['info'] = $list;
            } else {
                $rarr['return_code'] = "SUCCESS";
                $rarr['return_msg'] = "SUCCESS";
                $rarr['result_code'] = "FAIL";
                $rarr['result_msg'] = "没有数据";
            }
            return $rarr;
        }
    }

    //积分商城商品
    /*
     * 参数
     * $id,$card_id
     */
    public function goodsdetail($id, $card_id)
    {
        $this->_init();
        $appid = $this->getappid($card_id);
        $CardGoods = new CardGoods();
        $info = $CardGoods->where(['id' => $id])->find();
        //检查商品状态
        $user['openid'] = Session::get($appid . '_openid');
        $arr['id'] = $id;
        $check_res = $this->check_goods($arr);
        $info['ver_statu'] = $check_res;
        $card['card_id'] = $card_id;
        //JSSDK
        $share['wxjssdk'] = $this->getsharejssdk($card_id);
        $share['wxjssdk'] = json_encode($share['wxjssdk']);
        $this->assign('user', $user);
        $this->assign('share', $share);
        $this->assign('card', $card);
        $this->assign('info', $info);
        return $this->fetch();
    }

    //订单详情
    /*
     * 订单id 会员卡$card_id
     *
     * $id $card_id
     */
    public function orderinfo($id, $card_id)
    {
        $this->_init();
        $appid = $this->getappid($card_id);
        $map['card_id'] = $card_id;
        $map['openid'] = Session::get($appid . '_openid');
        $map['have'] = 1;
        $map['card_type'] = 'MEMBER_CARD';
        $CardUserGet = new CardUserGet();
        $info = $CardUserGet->where($map)->find();
        if ($info) {
            $mab['openid'] = Session::get($appid . '_openid');
            $mab['card_id'] = $card_id;
            $mab['id'] = $id;
            $CardGoods = new CardGoods();
            $CardOrder = new CardOrder();
            $order = $CardOrder->where($mab)->find();
            $goods = $CardGoods->where('id', $order['gid'])->find();
            $this->assign('goods', $goods);
            $this->assign('order', $order);
            return $this->fetch();
        } else {
            $this->redirect('Carduser/weboff', ['card_id' => $card_id]);
        }
    }

    /*
     * 提交订单
     * 参数
     * $id $card_id
     */
    public function orderadd($id, $card_id)
    {
        $appid = $this->getappid($card_id);
        if (Request()->isPost()) {
            $arr = request()->post();

            $openid = Session::get($appid . '_openid');
            $CardGoods = new CardGoods();
            $CardUserGet = new CardUserGet();
            $user = $CardUserGet->where(['openid' => $openid,'card_id' => $card_id])->field('bonus,id')->find();
            if ($user['bonus'] >= $arr['goods_price'] || $user['bonus'] == $arr['goods_price']) {
                $goods = $CardGoods->where('id', $arr['gid'])->find();
                $map['card_id'] = $arr['card_id'];
                $map['openid'] = Session::get($appid . '_openid');
                $data['uid'] = $user['id'];
                $data['card_id'] = $goods['card_id'];
                $data['goods_card_id'] = $goods['goods_card_id'];
                $data['openid'] = Session::get($appid . '_openid');
                $data['code'] = $arr['code'];
                $data['gid'] = $arr['gid'];
                $data['goods_name'] = $goods['goods_name'];
                $data['goods_type'] = $goods['goods_type'];
                $data['goods_img'] = $goods['goods_img'];
                $data['price'] = $arr['goods_price'];
                $data['goods_info'] = json_encode($goods, JSON_UNESCAPED_UNICODE);
                $data['create_time'] = time();
                $CardOrder = new CardOrder();
                $add = $CardOrder->allowField(true)->save($data);
                if ($add == false) {
                    $this->error('兑换失败', '', 1);
                } else {
                    $data['name'] = $arr['name'];
                    $res = $this->updatebonus($data);
                    if ($res == '0') {
                        //修改库存
                        $CardGoods->where('id', $arr['gid'])->setDec('stock');
                        $CardGoods->where('id', $arr['gid'])->setInc('getsume');
                        //同步积分状态
                        $resu['tplmsg_info'] = json_encode($res, JSON_UNESCAPED_UNICODE);
                        $order_id = $CardOrder->id;
                        $CardOrder->save($resu, ['id' => $order_id]);
                        $this->redirect(url('cardshop/addcard', ['order_id' => $order_id]));
                    } else {
                        $this->error('兑换失败', url('carduser/index', ['card_id' => $card_id]), 1);
                    }
                }
            } else {
                $this->success('积分不足', url('carduser/index', ['card_id' => $card_id]), 1);
            }
        } else {
            $this->_init();
            $openid = Session::get($appid . '_openid');
            $CardGoods = new CardGoods();
            $CardUserGet = new CardUserGet();
            $goods = $CardGoods->where(array('id' => $id))->find();
            $user = $CardUserGet->where(['openid' => $openid, 'card_id' => $card_id])->find();
            //JSSDK
            $share['wxjssdk'] = $this->getsharejssdk($card_id);
            $share['wxjssdk'] = json_encode($share['wxjssdk']);
            $this->assign('share', $share);
            $this->assign('user', $user);
            $this->assign('goods', $goods);
            return $this->fetch();
        }
    }


    //发放卡
    /*
     * 参数
     * $order_id
     */
    public function addcard($order_id)
    {
        $CardOrder = new CardOrder();
        $CardUserGet = new CardUserGet();
        $order = $CardOrder->where('id', $order_id)->find();
        $openid = $order['openid'];
        if ($order['statu'] < '2') {
            $user = $CardUserGet->where(['openid' => $openid, 'card_id' => $order['card_id']])->find();
//            if ($user['bonus'] > $order['price'] || $user['bonus'] == $order['price']) {
            $arr['card_id'] = $order['goods_card_id'];
            $arr['openid'] = $openid;
            //更新订单状态
//            $data['statu'] = '2';
//            $CardOrder->save($data, ['id' => $order_id]);
            //发放
            $arrs['card_id'] = $arr['card_id'];
            $arrs['openid'] = $arr['openid'];
            $arrs['outer_str'] = 'shopExch_' . $order_id;
            $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            $options = $this->options($arr['card_id']);
            $weObj = new Wxobjopen($options);
            $card = $this->put($arrs);
            $jssdk = $weObj->get_card_JsSign($url);
            $this->assign('card', $card);
            $this->assign('jssdk', $jssdk);
            return $this->fetch();
//            } else {
//                $this->success('积分不足', url('carduser/index', ['card_id' => $order['card_id']]), 1);
//            }
        } else {
            $this->success('订单已完成，请勿重复打开！', url('carduser/index', ['card_id' => $order['card_id']]), 1);
        }
    }

    //检查商品
    /*
     * 参数  商品id
     * $arr['id']
     *
     */
    private function check_goods($arr)
    {
        $CardGoods = new CardGoods();
        $map['id'] = $arr['id'];
        $goods = $CardGoods->where($map)->find();
        $time = time();
        //判断商品是否过期
        if ($goods['end_time'] > $time) {
            $data['ver_statu'] = 1;         //正常
            //判断是否有库存
            if ($goods['stock'] > $goods['getsume']) {
                $data['ver_statu'] = 1;         //正常
                //判断商品类型
                if ($goods['goods_type'] == 'card_dis') {
                    $data['ver_statu'] = 1;         //正常
//                    //判断卡券过期
                    if (filteroffcard($goods['goods_card_id']) == true) {
                        $data['ver_statu'] = 1;         //正常
                    } else {
                        $data['ver_statu'] = 16;        //卡券已过期 / 无库存
                    }
                } else {
                    $data['ver_statu'] = 17;         //红包类型未开放
                }
            } else {
                $data['ver_statu'] = 18;         //商品没有库存
            }
        } else {
            $data['ver_statu'] = 19;        //商品超过时间
        }
    }

    //投放卡
    /*
     *  $card_id $openid
     */
    private function put($arr)
    {
        $options = $this->options($arr['card_id']);
        $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $weObj = new Wxobjopen($options);
        $noncestr = $weObj->generateNonceStr();
        $res['config'] = $weObj->getJsSign($url, '', $noncestr);
        $res['config']['debug'] = true;
        $res['config']['jsApiList'] = array('addCard', 'openCard', 'chooseCard');
        $res['card_id'] = $arr['card_id'];
        $outer_str = $arr['outer_str'];
        $res['addcard'] = $weObj->wxAddCard($arr['openid'], $arr['card_id'], $noncestr, $outer_str);
        return $res;
    }

    //更新会员数据
    /*
     * $arr['card_id'] / $arr['code'] / $arr['price'] / $arr['name'] / $data['add_bonus']
     *
     */
    public function updatebonus($arr)
    {
//        $data = array(
//            'card_id' => $arr['card_id'],
//            'code' => $arr['code'],
//            'add_bonus' => -$arr['price'],
//            'record_bonus' => '积分兑换:' . $arr['name'],
//            "notify_optional" => array(
//                "is_notify_bonus" => true,
//                "is_notify_balance" => true,
//                "is_notify_custom_field1" => true
//            )
//        );
//        $options = $this->options($arr['card_id']);
//        $weObj = new Wxobjopen($options);
//        $res = $weObj->updateUserInfo($data);
//        if ($res['errcode'] == 0) {
            $CardUserGet = new CardUserGet();
            $user = $CardUserGet->where(['card_id' => $arr['card_id'],'code'=>$arr['code']])->field('mid,id,top_mid,code,nickname')->find();
            $bonus['mid'] = $user['mid'];
            $bonus['del_bonus'] = abs($arr['price']);
            $bonus['record_bonus'] = '积分兑换:' . $arr['name'];
            $bonus['openid'] = $arr['openid'];
            $bonus['card_id'] = $arr['card_id'];
            $bonus['type'] = 4;            //类型
            $bonus['cate'] = 1;         //类别
            $bonus['reason'] = 11;      //原因
            $bonus['source'] = 11;      //渠道
            $bonus['create_time'] = time();
            $bonus['outerstr'] = 'BONUSSHOP';
//            $bonus['tplmesg_info'] = json_encode($res);
            $CardUserUpdate = new CardUserUpdate();
            $CardUserUpdate->allowField(true)->save($bonus);
            $map['openid'] = $bonus['openid'];
            $map['card_id'] = $bonus['card_id'];
//            $CardUserGet->where($map)->setField('bonus', $res['result_bonus']);
            //END
            $datass['card_id'] = $bonus['card_id'];
            $datass['code'] = $arr['code'];
            $datass['num'] = $arr['price'];
            $datass['remark'] = '积分兑换:' . $arr['name'];
            $datass['type'] = 2;
            $datass['cate'] = 9;
            $datass['pay_cate'] = 21;
            $datass['source'] = 'online';
            $datass['orderid'] = '';
            $datass['bd_cate'] = 'bonus';
            $datass['action_user'] = 'BONUSSHOP';//操作人
            $Fztest = new WnCardObj($datass);
            $Fztest->init();
            return '0';
//        } else {
//            return "1";
//        }
    }

    //积分记录
    private function rec_user_bonus($param){
        try{
            $data['card_id'] = $param['card_id'];
            $data['code'] = $param['code'];
            $data['num'] = $param['add_bonus'];
            $data['remark'] = $param['record_bonus'];
            $data['type'] = 2;
            $data['cate'] = 9;
            $data['pay_cate'] = 0;
            $data['source'] = 'online';
            $data['orderid'] = '';
            $data['bd_cate'] = 'bonus';
            $data['action_user'] = 'SHAREGIFT';//操作人
            $data['orderid'] = $param['orderid'];
            $Fztest = new WnCardObj($data);
            $Fztest->init();
        }catch (\Exception $e) {
            $res = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
//            file_put_contents('/data2/html/payos/qrcodepaybonus.txt', 'e:' . json_encode($res, JSON_UNESCAPED_UNICODE), FILE_APPEND);
        }
    }

    //余额
    //  mid  card_id  code  orderid  add_balance username
    private function rec_user_balance($param){
        try{
            $option['mid'] = $param['mid'];
            $option['card_id'] = $param['card_id'];
            $option['code'] = $param['code'];
            $option['orderid'] = $param['orderid'];
            $option['num'] =  $param['add_balance'];
            $option['bd_cate'] = 'balance';
            $option['type'] = 2;//变动 1增加 2减少
            $option['cate'] = 2;  //变动类型
            $option['pay_cate'] = 8; //支付方式
            $option['source'] = 'web';  //来源
            $option['kuantai'] = 'web';  //款台
            $option['remark'] = $param['record_balance']; //备注
            $option['action_user'] = $param['username'];//操作人
            $Fztest = new WnCardObj($option);
            $res = $Fztest->init();
            $ActionLogs=new ActionLogs();
            $ActionLogs->writelog("payos","wxcard","paycards","1:",$option);
            $ActionLogs->writelog("payos","wxcard","paycards","2:",$res);

        }catch (\Exception $e) {
            $res = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
            $res = '';
        }
        return $res;
    }

    //分享jssdk
    /*
     * $card_id
     */
    private function getsharejssdk($arr)
    {
//        return $arr;
        $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $options = $this->options($arr);
        //分享
        $weObj = new Wxobjopen($options);
        $jssdk = $weObj->getJsSign($url);
        $wxJsSdk = [
            'debug' => false,
            'appId' => $jssdk['appId'],
            'timestamp' => $jssdk['timestamp'],
            'nonceStr' => $jssdk['nonceStr'],
            'signature' => $jssdk['signature'],
            'jsApiList' => [
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'onMenuShareQQ',
                'onMenuShareQZone',
                'closeWindow',
                'hideAllNonBaseMenuItem',
            ]
        ];
        return $wxJsSdk;
    }

    //付费券支付
    public function paycardpay(Request $request)
    {
        $CardPaycardlog = new CardPaycardlog();
        if ($request->isAjax()) {
            $param = $request->post();
            if ($param['pay_type'] == 'card_pay') {
                $Paylog = new Paylog();
                $payinfo = $Paylog->where('orderid',$param['orderid'])->field('openid,price,orderid,mid,pay_statu')->find();
                //END
                if ($payinfo['pay_statu'] == 1) {
                    $jsApiObj = ['code' => 9002, 'message' => '此订单已支付！'];
                }else{

                    //END
                    $CardUserGet = new CardUserGet();
                    $maps['openid'] = $payinfo['openid'];
                    $maps['card_type'] = 'MEMBER_CARD';
                    $user = $CardUserGet->where($maps)->field('balance,nickname,card_id,code')->find();
                    if ($payinfo['price'] <= $user['balance']) {
                        $datas['mid'] = $payinfo['mid'];
                        $datas['orderid'] = $payinfo['orderid'];
                        $datas['add_balance'] = $payinfo['price'];
                        $datas['card_id'] = $user['card_id'];
                        $datas['code'] = $user['code'];
                        $datas['username'] = $user['nickname'];
                        $datas['record_balance'] = '付费券购买';
                        $res_id = $this->rec_user_balance($datas);
                        //END
                        $data['pay_cate'] = 'pay';
                        $data['pay_fs'] = '8';
                        $data['pay_statu'] = '1';
                        $map['orderid'] = $param['orderid'];
                        $Paylog->allowField(true)->save($data,$map);
                        //END
                        if ($res_id) {
                            $jsApiObj = ['code' => 0, 'message' => '支付成功！'];
                        } else {
                            $jsApiObj = ['code' => 9002, 'message' => '支付失败！'];
                        }
                    } else {
                        $jsApiObj = ['code' => 9002, 'message' => '支付失败，余额不足'];
                    }
                }
                //END
            }else {
                //微信支付
                $Merchant = new Merchant();
                $Agent = new Agent();
                $WxOpen = new WxOpen();
                $Paylog = new Paylog();
                $param = $request->post();
                $cinfo = $CardPaycardlog->relation('Paycardinfo')->where(array('id' => $param['id']))->find();
                $payinfo = $Paylog->where('orderid',$cinfo['orderid'])->field('openid,price,orderid,mid,pay_statu')->find();
                if ($payinfo['pay_statu'] == 1) {
                    $jsApiObj = ['code' => 9002, 'message' => '此订单已支付！'];
                }else {
                    $map['id'] = $cinfo['mid'];
                    $config = $Merchant->where($map)->find();
                    $agent = $Agent->where(array('id' => $config['agent']))->find();
                    $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
                    $userwx = $WxOpen->where(array('id' => $config['wx_open_id']))->find();
                    $options = array(
                        'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
                        'partnerid' => $agent['partnerid'], // 财付通商户身份标识
                        'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
                    );
                    $weObj = new Wxobjopen($options);
                    $price = $cinfo['price'];
                    $appid = $users['authorizer_appid'];
                    $mch_id = $agent['partnerid'];
                    $out_trade_no = $cinfo['orderid'];
                    $body = "付费券购买";
                    $sub_mch_id = $config['sub_mch_id'];
                    $sub_appid = $userwx['authorizer_appid'];
                    $total_fee = $price * 100;
                    $sub_openid = $cinfo['openid'];
                    $notify_url = 'https://' . $_SERVER ['SERVER_NAME'] . '/api.php';
                    $spbill_create_ip = $_SERVER["REMOTE_ADDR"];
                    $nonce_str = $weObj->generateNonceStr();
                    $pay_xml = $weObj->createPackageXml2($appid, $sub_appid, $mch_id, $sub_mch_id, $nonce_str, $body, $out_trade_no, $total_fee, $spbill_create_ip, $notify_url, '', $sub_openid);
                    $pay_xml = $weObj->get_pay_id($pay_xml);
                    if ($pay_xml['return_code'] == 'SUCCESS') {
                        $prepay_id = $pay_xml['prepay_id'];
                        $jsApiObj["appId"] = $appid;
                        $timeStamp = time();
                        $jsApiObj["timeStamp"] = "$timeStamp";
                        $jsApiObj["nonceStr"] = $nonce_str;
                        $jsApiObj["package"] = "prepay_id=" . $prepay_id;
                        $jsApiObj["signType"] = "MD5";
                        $jsApiObj["paySign"] = $weObj->getPaySignature($jsApiObj);
                    } else {
                        $jsApiObj = ['code' => 9002, 'message' => '支付失败！'];
                    }
                }
            }
            return json($jsApiObj);
        }else {
            $arr = request()->param();
            $cinfo = $CardPaycardlog->relation('Paycardinfo')->where(array('id' => $arr['id']))->find();
            if (isset($arr['card_id'])) {
                $card_id = $arr['card_id'];
            } else {
                $card_id = $this->get_cardid_mid($arr['mid']);
            }
            $card['card_id'] = $card_id;
            $cardinfos = $this->getuserinfo($card);
            //END
            $card['logo_url'] = cardgetinfo($card['card_id'], 0, 0);
            $this->assign('card', $card);
            $this->assign('cinfo', $cinfo);
            //END
            if ($cardinfos) {
                $cardinfo = "";
                $url = "https://" . $_SERVER['HTTP_HOST'] . "/mobile.php?s=/carduser/recharge&card_id=" . $card['card_id'];
                $cardinfo2 = '<span class="wxpay_card" >会员卡<b style="color:black">[余额:' . $cardinfos['balance'] . ']</b><span><a href="'.$url.'">[在线充值]</a></span></span>';
            } else {
                $url = "https://" . $_SERVER['HTTP_HOST'] . "/mobile.php?s=/carduser/opencard/card_id/" . $card['card_id'];
                $cardinfo = "";
                $cardinfo2 = "<span class='wxpay_card'>该商户可领取会员卡<span><a href='$url'>点此领取会员卡></a></span></span>";
            }
            $this->assign('cardinfo', $cardinfo);
            $this->assign('cardinfo2', $cardinfo2);
            return $this->fetch();
        }

    }

    public function addorder()
    {
        if (request()->isAjax()) {
            $id = request()->post('id');
            if (get_is_paycardnum($id) == false) {
                return ['code' => 9003, 'message' => '该商品没有库存'];
            }
            $CardPaycard = new CardPaycard();
            $cinfo = $CardPaycard->where(array('id' => $id))->find();
            $buycount = $this->getxg($cinfo['id'], request()->post('openid'));
            if ($cinfo['homebuy'] <= $buycount) {
                return ['code' => 9004, 'message' => '该商品限购' . $cinfo['homebuy'] . "件，您已购买" . $buycount . "件"];
            }
            $orderid = $this->getorderid($cinfo['mid']);
            $data['mid'] = $cinfo['mid'];
            $data['openid'] = request()->post('openid');
            $data['orderid'] = $orderid;
            $data['price'] = $cinfo['price'];
            $data['fid'] = $cinfo['id'];
            $CardPaycardlog = new CardPaycardlog();
            $add = $CardPaycardlog->save($data);
            $data['orderid'] = $orderid;
            $data['mid'] = $cinfo['mid'];
            $data['openid'] = request()->post('openid');
            $data['pay_statu'] = 0;
            $data['price'] = $cinfo['price'];
            $data['yf_price'] = $cinfo['price'];
            $data['zk_price'] = $data['yf_price'] - $data['price'];
            $data['add_time'] = time();
            $data['attach'] = 'ffcard';
            $data['cz_card_id'] = request()->post('get_card_id');
            $Paylog = new Paylog();
            $add = $Paylog->allowField(true)->save($data);
            if ($add) {
                $data2['code'] = 0;
                $CardUserGet = new CardUserGet();
                $card_id = $CardUserGet->where(['id' => request()->post('get_card_id')])->value('card_id');
                $data2['data']['url'] = url('Cardshop/paycardpay', array('id' => $CardPaycardlog->id, 'card_id' => $card_id));
            } else {
                $data2['code'] = 9001;
                $data2['data']['message'] = "操作失败";
            }
            return json($data2);
        }


    }

    public function getxg($fid, $openid)
    {
        $map['paystatu'] = 1;
        $map['fid'] = $fid;
        $map['openid'] = $openid;
        $CardPaycardlog = new CardPaycardlog();
        $count = $CardPaycardlog->where($map)->count();
        return $count;


    }

    //检查支付状态
    public function paysuccess()
    {
        if (request()->isAjax()) {
            $request = request();
            $param = $request->post();
            if ($param['pay_type'] == 'card_pay'){
                $Paylog = new Paylog();
                $payinfo = $Paylog->where('orderid',$param['orderid'])->field('orderid,pay_statu,pay_fs,mid,openid,cz_card_id')->find();
                if ($payinfo['pay_statu'] == 1 && $payinfo['pay_fs'] == 8){
                    $CardPaycardlog = new CardPaycardlog();
                    $Paylog = new Paylog();
                    $getcardid = $Paylog->where(['orderid' => $param['orderid']])->value('cz_card_id');
                    $arr['card_id'] = $this->getcardid($getcardid);
                    $arr['give_rec_id'] = $CardPaycardlog->where(['orderid' => $param['orderid']])->value('id');
                    $arr['mid'] = $payinfo['mid'];
                    $datas['orderid'] = $payinfo['orderid'];
                    $datas['mid'] = $payinfo['orderid'];
                    $datas['get_card_id'] = $payinfo['cz_card_id'];
                    $datas['openid'] = $payinfo['openid'];
                    $Wxpay = new Wxpay();
                    $Wxpay->pay_card_put($datas);
                    $data['code'] = 0;
                    $data['data']['url'] = $this->getpaycardurl($arr);
                    $data['message'] = '支付成功!';
                }else{
                    $data['code'] = 1;
                    $data['message'] = '支付失败!';
                }
            }else {
                $Merchant = new Merchant();
                $Agent = new Agent();
                $WxOpen = new WxOpen();
                $map['id'] = $request->post('id');
                $config = $Merchant->where($map)->find();
                $agent = $Agent->where(array('id' => $config['agent']))->find();
                $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
                $userwx = $WxOpen->where(array('id' => $config['wx_open_id']))->find();
                $options = array(
                    'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
                    'partnerid' => $agent['partnerid'], // 财付通商户身份标识
                    'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
                );
                $weObj = new Wxobjopen($options);
                $appid = $users['authorizer_appid'];
                $mch_id = $agent['partnerid'];
                $out_trade_no = $request->post('orderid');
                $nonce_str = $weObj->generateNonceStr();
                $sub_mch_id = $config['sub_mch_id'];
                $sub_appid = $userwx['authorizer_appid'];
                $pay_xml = $weObj->createOrderXml($appid, $mch_id, $sub_appid, $sub_mch_id, $out_trade_no, $nonce_str);
                $payorder_xml = $weObj->getPayNum($pay_xml);
                $pay_zt = $payorder_xml['trade_state'];
                if ($pay_zt == "SUCCESS") {
                    $CardPaycardlog = new CardPaycardlog();
                    $Paylog = new Paylog();
                    $getcardid = $Paylog->where(['orderid' => $out_trade_no])->value('cz_card_id');
                    $arr['card_id'] = $this->getcardid($getcardid);
                    $arr['give_rec_id'] = $CardPaycardlog->where(['orderid' => $out_trade_no])->value('id');
                    $arr['mid'] = $map['id'];
                    $data['code'] = 0;
                    $data['data']['url'] = $this->getpaycardurl($arr);
                    $data['message'] = '支付成功!';
                } else {
                    $data['code'] = 1;
                    $data['message'] = '支付失败!';
                }
            }
            return json($data);
        }
    }

    //获取card_id
    private function getcardid($id)
    {
        $CardUserGet = new CardUserGet();
        $card_id = $CardUserGet->where(['id' => $id])->value('card_id');
        return $card_id;
    }

    //付费购券领取链接
    private function getpaycardurl($arr)
    {
        $Merchant = new Merchant();
        $top_mid = $Merchant->where(array('id'=>$arr['mid']))->value('top_mid');
        $Platurl = new Platurl();
        $notify_url = $Platurl->getagenturl('top_mid', $top_mid);
        $url = $notify_url . '/mobile.php?s=/cardget/getpaycards/mid/' . $arr['mid'] . '/rec_id/' . $arr['give_rec_id'];
        return $url;
    }

    private function getorderid($sh)
    {
        $order = "H" . $sh . "-" . date('YmdHis') . rand(10000, 99999);
        return $order;

    }


}
